package org.buptsse.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.buptsse.study.MyAdapter;
import org.buptsse.ui.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PostReplyActivity extends ListActivity {
	// ListView myListView;

	TextView replyNumView = null;
	//ImageView photo = null;
	private Handler dialogHandler = null;
	ProgressDialog myDialog;
	private final int finish = 0;
	private final int end = 1;
	private static final int DIALOG = 1;
	private static final int PROGRESSDIALOG = 2;
	private static final int PROGRESS = 3;
	MyAdapter myAdapter;
	HttpResponse response;
	HttpClient client;
	HttpPost post;
	List<NameValuePair> parameter;
	StringBuilder builder;
	BufferedReader reader;
	//Bitmap bitmap = null;
	String replyContent, replynum, title, time, username, postid, uri,
			defuri = "http://rebook-photo.stor.sinaapp.com/20120320191559.jpg";
	String myName;
	ArrayList<HashMap<String, String>> replylist = new ArrayList<HashMap<String, String>>();

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	class Init extends Thread {
		public void run() {
			client = new DefaultHttpClient();
			post = new HttpPost("http://rebook.sinaapp.com/searchphoto.php");
			parameter = new ArrayList<NameValuePair>();
			parameter.add(new BasicNameValuePair("username", username));
			try {
				post.setEntity(new UrlEncodedFormEntity(parameter));
				response = client.execute(post);
				reader = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent()));
				builder = new StringBuilder();
				for (String s = reader.readLine(); s != null; s = reader
						.readLine()) {
					builder.append(s);
				}
				if (builder.toString() == null) {
					//bitmap = getImage(defuri);
				} else {
					//bitmap = getImage(builder.toString());
				}
			} catch (ClientProtocolException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			GetJsonArray();
			if (dialogHandler != null)
				dialogHandler.sendEmptyMessage(end);
		}
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.post);
		showDialog(PROGRESS);
		username = this.getIntent().getStringExtra("username");
		postid = this.getIntent().getStringExtra("postid");
		title = this.getIntent().getStringExtra("title");
		time = this.getIntent().getStringExtra("time");
		replynum = this.getIntent().getStringExtra("replynum");
		replyContent = this.getIntent().getStringExtra("content");
		//photo = (ImageView) findViewById(R.id.photo);
		TextView titleView = (TextView) findViewById(R.id.posttitle);
		TextView userView = (TextView) findViewById(R.id.username);
		TextView timeView = (TextView) findViewById(R.id.time);
		TextView contentView = (TextView) findViewById(R.id.content);
		replyNumView = (TextView) findViewById(R.id.replynum);
		titleView.setText(title);
		userView.setText(username);
		timeView.setText(time);
		contentView.setText(replyContent);
		replyNumView.setText(replynum);

		Button replyButton = (Button) findViewById(R.id.replyButton);
		replyButton.setOnClickListener(new replyButtonListener());

		dialogHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case finish:
					myAdapter = new MyAdapter(PostReplyActivity.this, replylist);
					setListAdapter(myAdapter);
					dismissDialog(PROGRESSDIALOG);
					break;
				case end:
					//photo.setImageBitmap(bitmap);
					myAdapter = new MyAdapter(PostReplyActivity.this, replylist);
					setListAdapter(myAdapter);
					dismissDialog(PROGRESS);
				}
			}
		};
	};

	private void postReply() {
		CloudLearningApp cloudApp = (CloudLearningApp) getApplication();
		myName = cloudApp.getUsername();
		HttpClient client = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		JSONArray jsonarray = null;
		HttpPost post = new HttpPost(
				"http://rebook.sinaapp.com/replypublish.php");
		List<NameValuePair> parameter = new ArrayList<NameValuePair>();
		parameter.add(new BasicNameValuePair("postid", postid));
		parameter.add(new BasicNameValuePair("username", myName));
		parameter.add(new BasicNameValuePair("content", replyContent));

		try {
			post.setEntity(new UrlEncodedFormEntity(parameter, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class replyButtonListener implements OnClickListener {
		public void onClick(View view) {
			showDialog(DIALOG);
		}
	}

	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		if (id == 1) {
			return this.buildDialog(PostReplyActivity.this);
		} else if (id == 2) {
			return this.buildProgressDialog(PostReplyActivity.this);
		} else if (id == 3) {
			return this.buildProgress(PostReplyActivity.this);
		} else {
			return null;
		}
	}

	protected void Afterpost() {
		dismissDialog(DIALOG);
		showDialog(PROGRESSDIALOG);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);
		switch (id) {
		case PROGRESSDIALOG:
			new GetData().start();
			break;
		case PROGRESS:
			new Init().start();
			break;
		}
	}

	private Dialog buildProgress(Context context) {
		Dialog resultDialog = new ProgressDialog(this);
		;
		resultDialog.setTitle("加载中……");
		((ProgressDialog) resultDialog)
				.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		return resultDialog;
	}

	private Dialog buildProgressDialog(Context context) {
		Dialog resultDialog = new ProgressDialog(this);
		;
		resultDialog.setTitle("正在发帖……");
		((ProgressDialog) resultDialog)
				.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		return resultDialog;

	}

	private Dialog buildDialog(Context context) {
		LayoutInflater inflater = (LayoutInflater) PostReplyActivity.this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		final View view = inflater.inflate(R.layout.edittext, null);

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("回帖").setView(view);
		builder.setMessage("请输入回复内容");
		builder.setPositiveButton("回复", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				EditText replyText = (EditText) view
						.findViewById(R.id.edittext);
				replyContent = replyText.getText().toString();
				if (replyContent.equals("")) {
					Toast.makeText(PostReplyActivity.this, "回复内容不能为空",
							Toast.LENGTH_SHORT).show();
				} else {
					replynum = String.valueOf(Integer.parseInt(replynum) + 1);
					replyNumView.setText(String.valueOf(replynum));
					replyText.setText(null);
					Afterpost();

				}
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				EditText replyText = (EditText) view
						.findViewById(R.id.edittext);
				// TODO Auto-generated method stub
				replyText.setText(null);
				dialog.dismiss();
			}
		});
		return builder.create();
	}

	public static Bitmap getImage(String Url) throws Exception {
		try {
			URL url = new URL(Url);
			String responseCode = url.openConnection().getHeaderField(0);
			if (responseCode.indexOf("200") < 0)
				throw new Exception("失败" + responseCode);
			return BitmapFactory.decodeStream(url.openStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new Exception(e.getMessage());
		}
	}

	class GetData extends Thread {
		public void run() {
			postReply();
			GetJsonArray();
			if (dialogHandler != null)
				dialogHandler.sendEmptyMessage(finish);
		}
	}

	private JSONArray GetJsonArray() {
		client = new DefaultHttpClient();
		builder = new StringBuilder();
		JSONArray jsonarray = null;
		post = new HttpPost("http://rebook.sinaapp.com/postreply.php");
		parameter = new ArrayList<NameValuePair>();
		parameter.add(new BasicNameValuePair("postid", postid));
		try {
			post.setEntity(new UrlEncodedFormEntity(parameter, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {

			e1.printStackTrace();
		}
		try {
			response = client.execute(post);
			reader = new BufferedReader(new InputStreamReader(response
					.getEntity().getContent()));
			builder = new StringBuilder();
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				builder.append(s);
			}
			if (builder.toString() == null) {
			} else {
				jsonarray = new JSONArray(builder.toString());
				JSONObject jsonObject;
				if (jsonarray != null) {
					replylist.clear();
					for (int i = 0; i < jsonarray.length(); i++) {
						jsonObject = jsonarray.getJSONObject(i);
						HashMap<String, String> map = new HashMap<String, String>();
						post = new HttpPost(
								"http://rebook.sinaapp.com/searchphoto.php");
						parameter = new ArrayList<NameValuePair>();
						parameter.add(new BasicNameValuePair("username",
								jsonObject.getString("username")));
						try {
							post.setEntity(new UrlEncodedFormEntity(parameter,
									HTTP.UTF_8));
						} catch (UnsupportedEncodingException e1) {

							e1.printStackTrace();
						}
						response = client.execute(post);
						reader = new BufferedReader(new InputStreamReader(
								response.getEntity().getContent()));
						builder = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader
								.readLine()) {
							builder.append(s);
						}
						System.out.println("photo---->" + builder.toString());
						map.put("username", jsonObject.getString("username"));
						map.put("time", jsonObject.getString("time"));
						map.put("content", jsonObject.getString("content"));
						//map.put("photo", builder.toString());
						replylist.add(map);
					}
				}
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			System.out.println("client---->" + e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO---->" + e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json---->" + e.toString());
			e.printStackTrace();
		}
		return jsonarray;
	}

}
